<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货源名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入货源名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货源地址" prop="address">
        <el-input
            v-model="queryParams.address"
            placeholder="请输入货源地址"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
            v-model="queryParams.price"
            placeholder="请输入价格"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" style="width: 150px" placeholder="请选择货源分类">
          <el-option
              v-for="dict in chooseCategory"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="isDriver()">
        <el-button
            type="warning"
            plain
            icon="Download"
            :disabled="multiple"
            @click="shopping"
        >下单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-if="isAuth()||isGoodsOwner()"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-if="isAuth()"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-if="isAuth()||isGoodsOwner()"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="货源编号" align="center" prop="id"/>
      <el-table-column label="货源名称" align="center" prop="name"/>
      <el-table-column label="货源地址" align="center" prop="address"/>
      <el-table-column label="货源分类" align="center" prop="categoryName"/>
      <el-table-column label="价格" align="center" prop="price"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isAuth()">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-show="total>0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @current-change="getList"
    />

    <!-- 添加或修改货源对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="货源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入货源名称"/>
        </el-form-item>
        <el-form-item label="货源地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入货源地址"/>
        </el-form-item>
        <el-form-item label="货源分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择货源分类">
            <el-option
                v-for="dict in categoryChildrenList"
                :key="dict.id"
                :label="dict.name"
                :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="逻辑删除列" prop="delFlag" v-if="isAuth()">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除状态">
            <el-option
                v-for="dict in del_flag_options"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {addOrder} from "@/api/order";
import {listCategory} from "@/api/category";
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/goods";
import {getCurrentInstance, reactive, ref, toRaw, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getMaxFloor, isAuth, isDriver, isGoodsOwner, parseTime} from "@/utils/common";
import request from "@/utils/request";

const {proxy} = getCurrentInstance();

const goodsList = ref([]);
const orderGoodsDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedOrderGoodsDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const categoryChildrenList = ref([])
const del_flag_options = [
  {
    value: 1,
    label: '已删除',
  },
  {
    value: 0,
    label: '未删除',
  }
]

const chooseCategory = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    address: null,
    categoryId: null,
    price: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

/** 查询货源列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
    goodsList.value.forEach(item => {
      console.log('item:', item.category_id)
      console.log('item:', item.categoryName)
      let needToAddCategory = {
        value: item.category_id,
        label: item.categoryName
      }
      if (!chooseCategory.value.some(item => item.value === needToAddCategory.value)) {
        // 如果没有找到相同的value，则将新对象添加到数组中
        chooseCategory.value.push(needToAddCategory);
      }
      console.log('item:', needToAddCategory)
      console.log('chooseCategory.value:', chooseCategory.value)
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    address: null,
    categoryId: null,
    price: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  chooseCategory.value = []
  categoryChildrenList.value = []
  orderGoodsDetailsList.value = [];
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getCategoryList()
  open.value = true;
  title.value = "添加货源";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getCategoryList()
  const _id = row.id || ids.value
  getGoods(_id).then(response => {
    form.value = response.data;
    orderGoodsDetailsList.value = response.data.orderGoodsDetailsList;
    open.value = true;
    title.value = "修改货源";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      form.value.orderGoodsDetailsList = orderGoodsDetailsList.value;
      if (form.value.id != null) {
        updateGoods(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除货源编号为"' + _ids + '"的数据项？').then(function () {
    return delGoods(_ids);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {
  });
}

/** 订单货源明细序号 */
function rowOrderGoodsDetailsIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 订单货源明细添加按钮操作 */
function handleAddOrderGoodsDetails() {
  let obj = {};
  orderGoodsDetailsList.value.push(obj);
}

/** 订单货源明细删除按钮操作 */
function handleDeleteOrderGoodsDetails() {
  if (checkedOrderGoodsDetails.value.length == 0) {
    ElMessage.error("请先选择要删除的订单货源明细数据");
  } else {
    const orderGoodsDetailss = orderGoodsDetailsList.value;
    const checkedOrderGoodsDetailss = checkedOrderGoodsDetails.value;
    orderGoodsDetailsList.value = orderGoodsDetailss.filter(function (item) {
      return checkedOrderGoodsDetailss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleOrderGoodsDetailsSelectionChange(selection) {
  checkedOrderGoodsDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('yang/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

function getCategoryList() {
  listCategory(queryParams.value).then(response => {
    if (response.code === 200) {
      let records = response.data
      console.log('records:', records);
      getChildrenList(records)
    }
  });
}

function getChildrenList(obj) {
  obj.forEach(function (item) {
    if (item.childrenList !== null && item.childrenList.length !== 0) {
      getChildrenList(item.childrenList)
    } else {
      categoryChildrenList.value.push(item)
    }
  })
}

/**
 * 下单
 */
function shopping(row) {
  const _ids = row.id || ids.value;
  addOrder(_ids).then(response => {
    ElMessage.success("新增成功");
    open.value = false;
    getList();
  });
}

getList();
</script>
